﻿/*
 * @brief
 * @author li yong (DogLee)
 * @email 20162439@qq.com
 * @version 1.0
 * @date 2019-06-05 15:46:00
 */
#include "logappendernet.h"

#include <QTcpSocket>
#include <QTcpServer>

#include <QTimer>
#include <QMutex>
#include <QThread>

Q_GLOBAL_STATIC(QMutex, lock)

LogAppenderNet::LogAppenderNet()
{
    m_tcpServer = new QTcpServer(this);
    m_tcpServer->listen(QHostAddress::Any, 9500);
    connect(m_tcpServer, &QTcpServer::newConnection, this, &LogAppenderNet::onNewConnection);

    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, &LogAppenderNet::onDump);
    m_timer->start(500);
}

LogAppenderNet::~LogAppenderNet()
{
}

void LogAppenderNet::append(const DebugMessage &message)
{
    if (message.content.contains("Could not read from input device (No such device)"))
        return;

    lock()->lock();
    m_messages.append(message);
    while (m_messages.size() > 1000)
    {
        m_messages.takeFirst();
    }
    lock()->unlock();
}

void LogAppenderNet::onNewConnection()
{
    auto socket = m_tcpServer->nextPendingConnection();
    if (m_tcpSocket != Q_NULLPTR)
    {
        socket->disconnectFromHost();
        socket->deleteLater();
    }
    else
    {
        m_tcpSocket = socket;
        connect(m_tcpSocket, &QTcpSocket::disconnected, [=](){
            m_tcpSocket->deleteLater();
            m_tcpSocket = Q_NULLPTR;
        });
    }
}

void LogAppenderNet::onDump()
{
    QMutexLocker locker(lock());
    if (m_messages.empty() || m_tcpSocket == Q_NULLPTR)
        return;

    QByteArray msgs;
    foreach (auto message, m_messages)
    {
        QString str = message.time + "[" + messageTypeCode(message.type) + "]" + message.context;
        str += " -> " + message.content + "\n";
        msgs.append(str.toLocal8Bit());
    }
    m_tcpSocket->write(msgs);
    m_messages.clear();
}
